package net.wanglu.www.spdr.main;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Properties;

import net.wanglu.www.spdr.dao.CorpusDAO;
import net.wanglu.www.spdr.digger.Digger;
import net.wanglu.www.spdr.entities.Corpus;
import net.wanglu.www.spdr.log.LoggerFactory;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class SpiderMain {

	public static final String SpiderCfgPath = "config\\config.properties";
	public static Properties SpiderProperties = null;
	
	private ArrayList<Digger> diggerList;
	private CorpusDAO corpusDAO;

	public ArrayList<Digger> getDiggerList() {
		return diggerList;
	}
	public void setDiggerList(ArrayList<Digger> diggerList) {
		this.diggerList = diggerList;
	}

	public CorpusDAO getCorpusDAO() {
		return corpusDAO;
	}
	public void setCorpusDAO(CorpusDAO corpusDAO) {
		this.corpusDAO = corpusDAO;
	}
	
	public static void initSys() throws Exception {
		SpiderProperties = new Properties();
		InputStream in = new FileInputStream(System.getProperty("user.dir")+File.separator+SpiderCfgPath);
		SpiderProperties.load(in);
		in.close();
	}
	
	public static SpiderMain initSpring() throws Exception {
		String appXML = SpiderProperties.getProperty("Spring");
		ApplicationContext ctx = new ClassPathXmlApplicationContext(appXML);
		return (SpiderMain) ctx.getBean("main");		
	}
	
	public static void initLog4j() throws Exception {
		String log4j = SpiderProperties.getProperty("Log4j");
		LoggerFactory.load(log4j);
	}
	/**
	 * @param args
	 * @throws Exception 
	 */
	public static void main(String[] args) {
		try{
			initSys();
			initLog4j();
		} catch (Exception e) {
			e.printStackTrace();
			return;
		}
		
		SpiderMain main = null;
		try{
			main = initSpring();			
		} catch (Exception e) {
			e.printStackTrace();
			LoggerFactory.SpiderLogger.trace("", e);
			return;
		}
		
		if ( main != null ) {
			ArrayList<Digger> diggerList = main.getDiggerList();
			CorpusDAO corpusDao = main.getCorpusDAO();
			
			for ( int i=0; i<diggerList.size(); i++) {
				Digger digger = diggerList.get(i);
				ArrayList<Corpus> corpuz = null;
				try {
					corpuz = digger.dig();					
				} catch (Exception e) {
					LoggerFactory.SpiderLogger.trace("", e);
				}
				if ( corpuz == null ) continue;
				
				for ( int j=0; j<corpuz.size(); j++) {
					Corpus c = corpuz.get(j);
					try {
						corpusDao.insertCorpus(c);
					} catch (Exception e) {
						LoggerFactory.SpiderLogger.trace("", e);
					}
				}
			}
		}
	}
}
